package com.haohan.jingyuan.customer.service;

import cn.hutool.json.JSONUtil;
import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerFileAuthMapper;
import com.haohan.jingyuan.customer.dao.CustomerFileMapper;
import com.haohan.jingyuan.customer.dao.CustomerInfoMapper;
import com.haohan.jingyuan.customer.dto.req.CreateFileAuthRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteFileAuthRequest;
import com.haohan.jingyuan.customer.dto.req.QueryFileAuthListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateFileAuthRequest;
import com.haohan.jingyuan.customer.dto.resp.FileAuthInfoResp;
import com.haohan.jingyuan.customer.dto.resp.FileAuthListResp;
import com.haohan.jingyuan.customer.entity.CustomerFile;
import com.haohan.jingyuan.customer.entity.CustomerFileAuth;
import com.haohan.jingyuan.customer.helper.FileAuthRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 客户文件授权服务实现类
 *
 * @ClassName CustomerFileAuthService
 * @Description 客户文件授权相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/11/05 14:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerFileAuthService {

    /**
     * 客户文件授权Mapper
     */
    private final CustomerFileAuthMapper customerFileAuthMapper;

    /**
     * 客户信息Mapper
     */
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 客户材料Mapper
     */
    private final CustomerFileMapper customerFileMapper;

    /**
     * 创建文件授权
     *
     * @param request 创建文件授权请求
     * @return 文件授权信息
     */
    public FileAuthInfoResp createFileAuth(CreateFileAuthRequest request) {
        // 校验客户ID是否存在
        if (customerInfoMapper.findByCustomerId(request.getCustomerId()) == null) {
            throw new BusinessException(ErrorEnum.CUSTOMER_NOT_FOUND);
        }

        // 当授权类型为2时，校验fileIds不为空
        if (request.getAuthType() == 2) {
            if (CollectionUtils.isEmpty(request.getFileIds())) {
                throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "授权类型为2时，文件id列表不能为空");
            }
            // 批量查询文件
            List<CustomerFile> customerFiles = customerFileMapper.selectByFileKeys(request.getFileIds());
            if (CollectionUtils.isEmpty(customerFiles) || customerFiles.size() != request.getFileIds().size()) {
                throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "文件不存在");
            }
            // 校验文件是否属于该客户
            for (CustomerFile customerFile : customerFiles) {
                if (!request.getCustomerId().equals(customerFile.getCustomerId())) {
                    throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "文件不属于该客户: " + customerFile.getFileKey());
                }
            }
        }

        // 检查(customerId, userName, ukid=0)是否已存在
        CustomerFileAuth existingAuth = customerFileAuthMapper.selectByCustomerIdAndUserName(
                request.getCustomerId(), request.getUserName());
        if (existingAuth != null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "该客户和用户名的授权记录已存在");
        }

        // 创建授权记录
        CustomerFileAuth customerFileAuth = new CustomerFileAuth();
        customerFileAuth.setCustomerId(request.getCustomerId());
        customerFileAuth.setAuthType(request.getAuthType());

        // fileIds转换为JSON字符串存储
        if (request.getAuthType() == 2 && !CollectionUtils.isEmpty(request.getFileIds())) {
            customerFileAuth.setFileIds(JSONUtil.toJsonStr(request.getFileIds()));
        } else {
            customerFileAuth.setFileIds(null);
        }

        customerFileAuth.setUserName(request.getUserName());
        // 密码使用MD5加密
        customerFileAuth.setPassWord(request.getPassword());
        // ukid默认为0
        customerFileAuth.setUkid(0L);
        EntityUtil.setCreateAndModifyInfo(customerFileAuth, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerFileAuthMapper.insert(customerFileAuth);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        FileAuthInfoResp resp = FileAuthRespHelper.convert2FileAuthInfoResp(customerFileAuth);
        return resp;
    }

    /**
     * 更新文件授权
     *
     * @param request 更新文件授权请求
     * @return 文件授权信息
     */
    public FileAuthInfoResp updateFileAuth(UpdateFileAuthRequest request) {
        // 查询记录是否存在
        Long id = Long.parseLong(request.getId());
        CustomerFileAuth customerFileAuth = customerFileAuthMapper.selectById(id);
        if (customerFileAuth == null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "授权记录不存在");
        }

        // 如果授权类型为2，需要校验fileIds
        if (request.getAuthType() == 1) {
            customerFileAuth.setFileIds(null);
        } else {

            if (CollectionUtils.isEmpty(request.getFileIds())) {
                throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "授权类型为2时，文件id列表不能为空");
            }
            // 批量查询文件
            List<CustomerFile> customerFiles = customerFileMapper.selectByFileKeys(request.getFileIds());
            if (CollectionUtils.isEmpty(customerFiles) || customerFiles.size() != request.getFileIds().size()) {
                throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "文件不存在");
            }
            // 校验文件是否属于该客户
            for (CustomerFile customerFile : customerFiles) {
                if (!customerFileAuth.getCustomerId().equals(customerFile.getCustomerId())) {
                    throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "文件不属于该客户: " + customerFile.getFileKey());
                }
            }
        }

        // 如果更新userName，需要检查新的(customerId, userName, ukid=0)是否已存在
        if (request.getUserName() != null && !request.getUserName().equals(customerFileAuth.getUserName())) {
            CustomerFileAuth existingAuth = customerFileAuthMapper.selectByCustomerIdAndUserName(
                    customerFileAuth.getCustomerId(), request.getUserName());
            if (existingAuth != null && !existingAuth.getId().equals(id)) {
                throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "该客户和用户名的授权记录已存在");
            }
        }

        // 更新授权记录信息
        if (request.getAuthType() != null) {
            customerFileAuth.setAuthType(request.getAuthType());
        }
        if (request.getUserName() != null) {
            customerFileAuth.setUserName(request.getUserName());
        }
        if (request.getPassword() != null) {
            // 密码使用MD5加密
            customerFileAuth.setPassWord(DigestUtils.md5Hex(request.getPassword()));
        }
        EntityUtil.setModifyInfo(customerFileAuth, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerFileAuthMapper.updateById(customerFileAuth);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        FileAuthInfoResp resp = FileAuthRespHelper.convert2FileAuthInfoResp(customerFileAuth);
        return resp;
    }

    /**
     * 删除文件授权
     *
     * @param request 删除文件授权请求
     * @return 删除结果
     */
    public boolean deleteFileAuth(DeleteFileAuthRequest request) {
        // 查询记录是否存在
        Long recordId = Long.parseLong(request.getId());
        CustomerFileAuth customerFileAuth = customerFileAuthMapper.selectById(recordId);
        if (customerFileAuth == null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "授权记录不存在");
        }

        // 设置ukid为记录主键id
        customerFileAuth.setUkid(recordId);
        // 逻辑删除
        EntityUtil.logicalDelete(customerFileAuth, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerFileAuthMapper.updateById(customerFileAuth);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return true;
    }

    /**
     * 查询文件授权列表
     *
     * @param request 查询文件授权列表请求
     * @return 文件授权列表
     */
    public FileAuthListResp queryFileAuthList(QueryFileAuthListRequest request) {

        // 根据客户ID查询授权列表（customerId为null时查询所有）
        List<CustomerFileAuth> authList = customerFileAuthMapper.selectByCustomerId(request.getCustomerId());

        // 转换为响应对象
        List<FileAuthInfoResp> authRespList = new java.util.ArrayList<>();
        if (authList != null) {
            for (CustomerFileAuth auth : authList) {
                authRespList.add(FileAuthRespHelper.convert2FileAuthInfoResp(auth));
            }
        }

        FileAuthListResp response = new FileAuthListResp();
        response.setAuthList(authRespList);
        return response;
    }
}

